package cn.gp.controller;

import cn.gp.common.R;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @ClassName CommonController
 * @Description 图片的上传与下载
 * @Author He_Guoping
 * @Date 2023/5/30 21:05
 * @Version 1.0
 */
@Log4j
@CrossOrigin
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${baseImgPath}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 使用UUID重新生成文件名
        String fileName = UUID.randomUUID() + suffix;

        // 确保文件路径存在
        File dir = new File(basePath);
        if(! dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + "/" + fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        try (InputStream is = new FileInputStream(basePath + "/" + name)) {
            OutputStream os = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[8192];
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
